package org.example.back.controller.user;

import jakarta.servlet.http.HttpSession;
import org.example.back.entity.user.UserSport;
import org.example.back.service.user.UserSportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user/sport")
public class UserSportController {

    @Autowired
    private UserSportService userSportService;

    // 添加运动记录
    @PostMapping("/add")
    public Map<String, Object> addSport(@RequestBody UserSport sport, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        sport.setUserId(userId);
        userSportService.addSportWithCalories(sport);
        return Map.of(
    "success", true,
    "message", "添加成功",
    "calories", sport.getCalories()
);
    }

    // 获取某日的运动记录
    @GetMapping("/day")
    public Map<String, Object> getDay(@RequestParam String date, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        List<UserSport> list = userSportService.getUserSportByDate(userId, LocalDate.parse(date));
        return Map.of("success", true, "data", list);
    }

    // 获取最近一周的运动汇总
    @GetMapping("/week")
    public Map<String, Object> getWeek(HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        List<Map<String, Object>> list = userSportService.getUserSportLastWeek(userId);
        return Map.of("success", true, "data", list);
    }

    // 获取最近一个月的运动汇总
    @GetMapping("/month")
    public Map<String, Object> getMonth(HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        List<Map<String, Object>> list = userSportService.getUserSportByWeekInMonth(userId);
        return Map.of("success", true, "data", list);
    }

    // 删除指定运动记录（通过 userId 和 startTime 定位）
    @DeleteMapping("/delete")
    public Map<String, Object> deleteSport(@RequestParam String startTime, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        userSportService.deleteUserSport(userId, LocalDateTime.parse(startTime));
        return Map.of("success", true, "message", "删除成功");
    }
}
